#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月16日

@author: chenyongbing
'''

'''
    定时更新 zhimind.mac_factory 中 mac对应的品牌关系

'''


import sys,os,re
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(current_dir,'../../'))
import urllib2
import logging
from base.localConfig import baseLocalConfig
from base.PyMySQL import ConnectMySQL
import commands


zhimind_host = baseLocalConfig.mysqlConfig['zhimind']['host']
zhimind_user = baseLocalConfig.mysqlConfig['zhimind']['user']
zhimind_passwd = baseLocalConfig.mysqlConfig['zhimind']['passwd']
zhimind_db = baseLocalConfig.mysqlConfig['zhimind']['db']

myZhimind = ConnectMySQL(zhimind_host,zhimind_user,zhimind_passwd,zhimind_db)


Facts = [['Apple','苹果',[]],
         ['Xiaomi','小米',['BeijingXiaomi']],
         ['Lenovo','联想',['Vuzix/Lenovo']],
         ['Samsung','三星',['ToshibaSamsung','VDDivision,Samsung']],
         ['Huawei','华为',['ShenzhenHuawei']],
         ['HTC','HTC',[]],
         ['LG','LG',[]],
         ['Nokia','诺基亚',[]],
         ['Coolpad','酷派',[]],
         ['Meizu','魅族',[]],
         ['Oppo','OPPO',['GUANGDONGOPPOMOBILE']],
         ['Gionee','金立',[]],
         ['Sony','索尼',[]],
         ['Smartisan','锤子',[]],
         ['Moto','Moto',[]],
         ['Zhongxing','中兴',['WuxiZhongxing','zte']],
         ['TCL','TCL',['ShenzhenTCL']]
         ]



class UpdateFactoryToDb(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
    def get_oui(self,url = 'http://standards-oui.ieee.org/oui.txt',Facts=[]):
        oui_file = os.path.join(current_dir,'../log/')+'oui.txt'
        print oui_file
        cmd = 'wget %s -O %s'%(url,oui_file)
        print cmd
        
        while 1:
            #if os.path.exists(oui_file):break
            x = commands.getstatusoutput(cmd)
            if x[0]==0:
                logging.info('down oui file success.')
                break
            errMsg = x[1]
            logging.error(errMsg)
        output = open(oui_file).read()
        datas = []
        for maptop,comp in  re.findall('([^\s]{2}-[^\s]{2}-[^\s]{2})\s*\(hex\)\s*([^\n]+)',output):
            #print maptop,comp
            maptop = re.sub('-',':',maptop.lower())
            for fact_en,fact_cn,fact_comps in Facts:
                for fact_key in [fact_en]+fact_comps:
                    if  re.search('^%s'%fact_key.lower(),comp.lower()):
                        print fact_en,fact_cn,maptop
                        datas.append([fact_en,fact_cn,maptop.upper(),fact_en,fact_cn])
                        break
        logging.info('Found %s Macs.'%len(datas))
        return datas
    
    def update_fact_to_db(self,tab='mac_factory',datas=[]):
        
        logging.info('Start To Insert.')
        #sql = 'insert ignore   '+tab+' (factory_en,factory_ch,mac) VALUES (%s,%s,%s)'
        sql = 'insert '+tab+' set factory_en=%s,factory_ch=%s,mac=%s ON DUPLICATE KEY UPDATE factory_en=%s,factory_ch=%s'
        myZhimind.executemany(sql,datas)
    
        
if __name__ == '__main__':
    myUpdateFactoryToDb = UpdateFactoryToDb()
    datas =  myUpdateFactoryToDb.get_oui(Facts=Facts)
    myUpdateFactoryToDb.update_fact_to_db(datas= datas)
